#include "viml/debugger_cli.h"
#include <algorithm>

namespace viml {

DebugHistory::DebugHistory() : current_index(0) {
}

void DebugHistory::add(const std::string& command) {
    if (command.empty()) {
        return;
    }

    // 如果历史记录满了，移除最旧的
    if (history.size() >= MAX_HISTORY) {
        history.erase(history.begin());
    }

    // 添加新命令到末尾
    history.push_back(command);

    // 重置当前索引到末尾（新的位置）
    current_index = history.size();
}

std::string DebugHistory::get_previous() {
    if (history.empty() || current_index == 0) {
        return "";
    }

    if (current_index == history.size()) {
        // 从最新位置向后
        current_index = history.size() - 1;
    } else {
        // 从当前位置向后
        current_index--;
    }

    return history[current_index];
}

std::string DebugHistory::get_next() {
    if (history.empty() || current_index >= history.size()) {
        return "";
    }

    current_index++;
    return (current_index < history.size()) ? history[current_index] : "";
}

std::string DebugHistory::get_current() const {
    if (history.empty() || current_index == 0 || current_index > history.size()) {
        return "";
    }

    size_t idx = (current_index == history.size()) ? history.size() - 1 : current_index - 1;
    return idx < history.size() ? history[idx] : "";
}

void DebugHistory::reset() {
    history.clear();
    current_index = 0;
}

std::vector<std::string> DebugHistory::get_all() const {
    return history;
}

} // namespace viml